/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.karol.lx.agent;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.rmi.server.UnicastRemoteObject;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.karol.lx.dispatcher.GradeRequest;

/**
 *
 * @author karol
 */
public class StandardGraderAgent extends UnicastRemoteObject implements IGraderAgent {
    
    private ArrayList<Grader> mGraders = new ArrayList<>();

    public StandardGraderAgent(int graderNum) throws RemoteException {
        super();
        
        for (int i = 0 ; i < graderNum ; i++) {
            try {
                mGraders.add(new Grader(InetAddress.getLocalHost().getHostAddress() + "-" + i));
            } catch (UnknownHostException ex) {
                Logger.getLogger(StandardGraderAgent.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public int getTotalGrader() {
        return mGraders.size();
    }

    @Override
    public ArrayList<Integer> getServedAction() {
        ArrayList<Integer> retval = new ArrayList<>();
        
        //TODO: fix this
        retval.add(0);
        retval.add(1);
        
        return retval;
    }

    @Override
    public int getAvalableGrader() {
        int retval = 0;
        for (Grader g : mGraders) {
            if (g.getStatus() == Grader.STATUS_IDLE)
                retval++;
        }
        return retval;
    }

    @Override
    public synchronized boolean offerRequest(GradeRequest pRequest) {
        for (Grader g : mGraders) {
            if (g.getStatus() == Grader.STATUS_IDLE) {
                g.grade(pRequest);
                break; //TODO: fix this
            }
        }
        
        return true;
    }

    @Override
    public boolean isRequestAcceptable(GradeRequest pRequest) throws RemoteException {
        //TODO: implement this
        return true;
    }
    
}
